package com.xihuanjun.sdk.dao;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xihuanjun.sdk.config.JSTConfig;
import com.xihuanjun.sdk.entity.JSTInout;
import com.xihuanjun.sdk.entity.JSTOut;
import com.xihuanjun.sdk.entity.JSTPageData;
import com.xihuanjun.sdk.entity.JSTResult;
import com.xihuanjun.sdk.enums.JSTMethod;
import com.xihuanjun.sdk.exception.NoDataException;
import com.xihuanjun.sdk.util.JsonUtils;
import com.xihuanjun.sdk.util.QMUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.GZIPInputStream;

@Slf4j
public abstract class BaseDao {


    private  final String SIGN_METHOD_MD5 = "md5";
    private  final String CHARSET_UTF8 = "utf-8";
    private  final String CONTENT_ENCODING_GZIP = "gzip";
    protected JSTConfig jstConfig;

    protected QMUtils qmUtils;

    @Autowired
    public void setQmUtils(QMUtils qmUtils) {
        this.qmUtils = qmUtils;
    }

    @Autowired
    public void setJstConfig(JSTConfig jstConfig) {
        this.jstConfig = jstConfig;
    }

    // region 公开方法

    /**
     * 奇门通用查询
     * @param map
     * @param method
     * @param clazz
     * @return
     * @param <T>
     * @throws IOException
     */
    public <T> List<T> qmListQuery(HashMap<String,String> map, JSTMethod method,TypeReference<List<T>> clsType) throws IOException {
        String s = qmUtils.doRequest(method.getMethodName(),map);
        JSTResult result = getResult(s,true);
        if(result.getSuccess()){
            HashMap resultMap = JsonUtils.json2map(s);
            LinkedHashMap pageDataMap = (LinkedHashMap)resultMap.get("response");
            String json;
            if(pageDataMap.containsKey("datas")){
                json=JsonUtils.object2Json(pageDataMap.get("datas"));
            }else if(pageDataMap.containsKey("orders")){
                json=JsonUtils.object2Json(pageDataMap.get("orders"));
            }else if(pageDataMap.containsKey("inventorys")){
                json=JsonUtils.object2Json(pageDataMap.get("inventorys"));
            }else{
                return null;
            }
            ObjectMapper mapper=new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
            List<T> pageData= (List<T>) mapper.readValue(json, clsType);
            return pageData;
        }else{
            throw new RuntimeException(result.getMsg());
        }

    }

    private <T> List<T> getDataFromPage(JSTPageData<T> pageData){
        if(pageData.getOrders()!=null){
            return pageData.getOrders();
        }
        if(pageData.getDatas()!=null){
            return pageData.getDatas();
        }
        if(pageData.getInventorys()!=null){
            return pageData.getInventorys();
        }
        return null;
    }

    /**
     * 聚水潭通用查询
     * @param map
     * @param method
     * @param clazz
     * @return
     * @param <T>
     */
    protected  <T> List<T> jstListQuery(Map map,JSTMethod method,TypeReference<List<T>> clsType) throws IOException {
        String s = doRequest(method.getMethodName(), JsonUtils.map2json(map));
        JSTResult result = getResult(s,false);
        if(result.getSuccess()){
            HashMap resultMap = JsonUtils.json2map(s);
            LinkedHashMap pageDataMap = (LinkedHashMap)resultMap.get("data");
            String json;
            if(pageDataMap.containsKey("datas")){
                json=JsonUtils.object2Json(pageDataMap.get("datas"));
            }else if(pageDataMap.containsKey("orders")){
                json=JsonUtils.object2Json(pageDataMap.get("orders"));
            }else if(pageDataMap.containsKey("inventorys")){
                json=JsonUtils.object2Json(pageDataMap.get("inventorys"));
            }else{
                throw new RuntimeException("没有数据key");
            }
            ObjectMapper mapper=new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
            List<T> pageData= (List<T>) mapper.readValue(json, clsType);
            return pageData;
        }
        throw new RuntimeException(result.getMsg());

    }


    // endregion

    protected JSTResult getResult(String resultJson,boolean isQM){
        JSTResult result=new JSTResult();
        HashMap map = JsonUtils.json2Object(resultJson, HashMap.class);
        if(isQM){
            LinkedHashMap response = (LinkedHashMap) map.get("response");
            if(response.get("flag")!=null && response.get("flag").toString().equals("failure")){
                result.setSuccess(false);
                result.setMsg(response.get("message").toString());
            }else{
                result.setSuccess(true);
            }
        }else{
            if(map.get("code").toString().equals("0")){
                result.setSuccess(true);
            }else{
                result.setSuccess(false);
                result.setMsg(map.get("msg").toString());
            }
        }
        return result;
    }



    /**
     * 发送一个jst接口请求
     * @param api 请求接口地址
     * @param bizJsonString biz参数字符串
     * @return
     * @throws IOException
     */
    protected String doRequest(String api,String bizJsonString) throws IOException {
        log.debug("发送聚水潭请求：{}",api);
        log.debug("参数：{}",bizJsonString);
        Map<String, String> params = new HashMap<String, String>();
        // 公共参数
        params.put("app_key", jstConfig.getAppKey());
        params.put("access_token", jstConfig.getToken());
        params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("version", "2");
        params.put("charset", "utf-8");
        // 业务参数
        params.put("biz", bizJsonString);
        // 签名参数
        params.put("sign", signTopRequest(params, jstConfig.getAppSecret(), SIGN_METHOD_MD5));
        // 调用API
        String e = callApi(new URL(jstConfig.getServerPath()+api), params);
        log.debug("请求结果：{}",e);
        return e;
    }


    /**
     * 从一个集合中获取第一条数据，没有返回null，如果有多条抛异常
     * @param list
     * @return
     * @param <T>
     */
    protected <T> T getOneFromList(List<T> list){
        if(list==null || list.size()==0){
            return null;
        }
        if(list.size()>1){
            throw new RuntimeException("获取一条数据，但总共"+list.size());
        }
        return list.get(0);
    }


    public HashMap getTokenInfo(){
        HashMap<String,String> map=new HashMap<>();
        map.put("token",jstConfig.getToken());
        return map;
    }



    /*
    -----------------------------------------下面代码都是聚水潭官网提供---------------------------------------------------

     */

    private  String signTopRequest(Map<String, String> params, String secret, String signMethod) throws IOException {
        // 第一步：检查参数是否已经排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 第二步：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        if (SIGN_METHOD_MD5.equals(signMethod)) {
            query.append(secret);
        }
        for (String key : keys) {
            String value = params.get(key);
            if (isNotEmpty(key) && isNotEmpty(value)) {
                query.append(key).append(value);
            }
        }
        return createSign(query.toString());
    }

    private  String createSign(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance(SIGN_METHOD_MD5);
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            int i = 0;
            while (i < j) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
                i++;
            }
            return new String(buf);
        } catch (Exception e) {
            return null;
        }
    }
    private  String callApi(URL url, Map<String, String> params) throws IOException {
        String query = buildQuery(params, CHARSET_UTF8);
        byte[] content = {};
        if (query != null) {
            content = query.getBytes(CHARSET_UTF8);
        }

        HttpURLConnection conn = null;
        OutputStream out = null;
        String rsp = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Host", url.getHost());
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + CHARSET_UTF8);
            out = conn.getOutputStream();
            out.write(content);
            rsp = getResponseAsString(conn);
        } finally {
            if (out != null) {
                out.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }

        return rsp;
    }
    private static String buildQuery(Map<String, String> params, String charset) throws IOException {
        if (params == null || params.isEmpty()) {
            return null;
        }

        StringBuilder query = new StringBuilder();
        Set<Map.Entry<String, String>> entries = params.entrySet();
        boolean hasParam = false;

        for (Map.Entry<String, String> entry : entries) {
            String name = entry.getKey();
            String value = entry.getValue();
            // 忽略参数名或参数值为空的参数
            if (isNotEmpty(name) && isNotEmpty(value)) {
                if (hasParam) {
                    query.append("&");
                } else {
                    hasParam = true;
                }

                query.append(name).append("=").append(URLEncoder.encode(value, charset));
            }
        }

        return query.toString();
    }

    private static boolean isNotEmpty(String value) {
        int strLen;
        if (value == null || (strLen = value.length()) == 0) {
            return false;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(value.charAt(i)) == false)) {
                return true;
            }
        }
        return false;
    }
    private  String getResponseAsString(HttpURLConnection conn) throws IOException {
        String charset = getResponseCharset(conn.getContentType());
        if (conn.getResponseCode() < 400) {
            String contentEncoding = conn.getContentEncoding();
            if (CONTENT_ENCODING_GZIP.equalsIgnoreCase(contentEncoding)) {
                return getStreamAsString(new GZIPInputStream(conn.getInputStream()), charset);
            } else {
                return getStreamAsString(conn.getInputStream(), charset);
            }
        } else {// Client Error 4xx and Server Error 5xx
            throw new IOException(conn.getResponseCode() + " " + conn.getResponseMessage());
        }
    }

    private  String getStreamAsString(InputStream stream, String charset) throws IOException {
        try {
            Reader reader = new InputStreamReader(stream, charset);
            StringBuilder response = new StringBuilder();

            final char[] buff = new char[1024];
            int read = 0;
            while ((read = reader.read(buff)) > 0) {
                response.append(buff, 0, read);
            }

            return response.toString();
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    }

    private  String getResponseCharset(String ctype) {
        String charset = CHARSET_UTF8;

        if (isNotEmpty(ctype)) {
            String[] params = ctype.split(";");
            for (String param : params) {
                param = param.trim();
                if (param.startsWith("charset")) {
                    String[] pair = param.split("=", 2);
                    if (pair.length == 2) {
                        if (isNotEmpty(pair[1])) {
                            charset = pair[1].trim();
                        }
                    }
                    break;
                }
            }
        }

        return charset;
    }
}
